import {
    getBridgeMonitor,
    getCraneDateLatest,
    getDustDateList,
    getFvsToken, getGantryMonitor,
    getLiftDateLatest,
    getSenceDetails,
    getStreamUrl, getWaterList
} from "@/api/api";
import {wind_Direction, wind_Force} from "@/sever/wind";
import hlsjs from "hls.js";
import EZUIKit from "ezuikit-js";
import {getFvsDetail} from "@/api/fvs";
import Hls from "hls.js";
import {
    bridge_params_data,
    crane_params_data,
    crawler_params_data,
    gantry_params_data,
    initParamsData, lift_params_data
} from "@/sever/fse-params-data";
import {
    initSceneTypeDataFn
} from "@/sever/scene-type-list";
import {getcrawlerlatest} from "@/api/crawler";
import {getElecHours, getEnergyElectricBoxLog, getwaterHours} from "@/api/energy";

export const senceBoard = {
    data() {
        return {
            detailsList: [],
            ratio: "",
            imgUrl: "",
            screenPre: "",
            screenWidth: document.body.clientWidth,
            //环境
            pm25: "",
            pm10: "",
            noise: "",
            envTemp: "",
            envRh: "",
            windDirection: "",
            windSpeed: "",
            tsp: "",
            atmos: "",
            windForce: "",

            // 水质
            ss: '',

            //毒害气体
            co: "",
            co2: "",
            h2s: "",
            ch4: "",
            o2: "",
            // 播放 hls 或者 ezuikit
            playModeFlag: false,
            //切换栏id
            tabType: '1',
            //切换栏列表
            tabList: [],
            //参数列表
            params_data: [],
            //参数全部列表
            params_data_all: [],

            //屏幕宽度比例
            clientWidthRate:'',
            //屏幕高度比例
            clientHeightRate:'',

            // 详情类型
            objType:'',

            navList: [],
            focus: null,
            focusId:"",
            showFlag:true,
            devName:"",
            devFlag:false,
            fimFlag:false,
            dataFlag:true,


        }
    },
    methods: {
        //窗口大小缩放监控
        resizeFn(){
            this.getProportion();
        },
        //获取计算比例
        getProportion() {
            this.clientWidthRate = this.$refs['screenPre'].clientWidth / 1600;
            this.clientHeightRate = this.$refs['screenPre'].clientHeight / 800;
        },
        // 获取切换栏id
        getTab(type) {
            this.params_data = this.params_data_all.filter(v => type == v.type);
        },
        //获取龙门吊数据
        getGantryMonitorFn(gantryId) {
            this.params_data = [];
            this.params_data_all = [];
            let params = {
                gantryId
            }
            getGantryMonitor(params).then(res => {
                if (res.code == 200) {
                    let obj = res.data;
                    let params_data = initParamsData(gantry_params_data, obj)
                    this.params_data = params_data.filter(v => this.tabType == v.type);
                    this.params_data_all = params_data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })

        },
        //获取架桥机数据
        getBridgeMonitorFn(bridgeId) {
            this.params_data = [];
            this.params_data_all = [];
            let params = {
                bridgeId
            }
            getBridgeMonitor(params).then(res => {
                if (res.code == 200) {
                    let obj = res.data;
                    let params_data = initParamsData(bridge_params_data, obj)
                    this.params_data = params_data.filter(v => this.tabType == v.type);
                    this.params_data_all = params_data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })

        },
        // 获取履带吊数据
        getCrawlerLatestFn(crawlerId) {
            this.params_data = [];
            this.params_data_all = [];
            let params = {
                crawlerId
            }
            getcrawlerlatest(params).then(res => {
                if (res.code == 200) {
                    let obj = res.data;
                    for (const objKey in obj) {
                        if (objKey == 'conditions') {
                            if (obj[objKey] == 0) {
                                obj[objKey] = '主臂工况'
                            }
                            if (obj[objKey] == 100) {
                                obj[objKey] = '塔况'
                            }
                            if (obj[objKey] == 200) {
                                obj[objKey] = '混合臂'
                            }
                            if (obj[objKey] == 300) {
                                obj[objKey] = '超起'
                            }
                            if (obj[objKey] == 400) {
                                obj[objKey] = '综合'
                            }
                        }
                    }
                    let params_data = initParamsData(crawler_params_data, obj)
                    this.params_data = params_data.filter(v => this.tabType == v.type);
                    this.params_data_all = params_data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })

        },
        // 获取电箱数据
        getEnergyElectricBoxLogFn(boxId) {
            let params = {
                boxId,
                startTime: this.$moment().subtract(1, "days").format('YYYY-MM-DD hh:mm:ss'),
                endTime: this.$moment().format('YYYY-MM-DD hh:mm:ss'),
            }
            getEnergyElectricBoxLog(params).then(res => {
                if (res.code == 200) {
                    let list = res.data.list;
                    if (list.length > 0) {
                        let tList = [
                            {
                                name: 't1',
                                type: 1,
                                value: list[list.length - 1].t1 || 0,
                                unit:'°C'
                            },
                            {
                                name: 't2',
                                type: 1,
                                value: list[list.length - 1].t2 || 0,
                                unit:'°C'
                            },
                            {
                                name: 't3',
                                type: 1,
                                value: list[list.length - 1].t3 || 0,
                                unit:'°C'
                            },
                            {
                                name: 't4',
                                type: 1,
                                value: list[list.length - 1].t4 || 0,
                                unit:'°C'
                            },
                        ];
                        let vList = [
                            {
                                name: 'v1',
                                type: 2,
                                value: list[list.length - 1].v1 || 0,
                                unit:'V'
                            },
                            {
                                name: 'v2',
                                type: 2,
                                value: list[list.length - 1].v2 || 0,
                                unit:'V'
                            },
                            {
                                name: 'v3',
                                type: 2,
                                value: list[list.length - 1].v3 || 0,
                                unit:'V'
                            },
                        ];
                        let cList = [
                            {
                                name: 'c1',
                                type: 3,
                                value: list[list.length - 1].c1 || 0,
                                unit:'A'
                            },
                            {
                                name: 'c2',
                                type: 3,
                                value: list[list.length - 1].c2 || 0,
                                unit:'A'
                            },
                            {
                                name: 'c3',
                                type: 3,
                                value: list[list.length - 1].c3 || 0,
                                unit:'A'
                            },
                        ];
                        let leakList = [
                            {
                                name: '漏电',
                                type: 4,
                                value: list[list.length - 1].leak || 0,
                                unit:'A'
                            },
                        ];
                        this.params_data_all = [...tList, ...vList, ...cList, ...leakList];
                        this.params_data = this.params_data_all.filter(v => this.tabType == v.type);
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        // 获取电表数据
        getElecHoursFn() {
            let params = {
                deptId:this.deptId,
                date: this.$moment().format('YYYY-MM-DD'),
            }
            getElecHours(params).then(res => {
                if (res.code == 200) {
                    let list = res.data.list;
                    if (list.length > 0) {
                        let params_data = [
                            {
                                name: '有功电能',
                                value: list[list.length - 1].positiveActive || 0,
                                unit:'KW-h'
                            },
                            {
                                name: '无功电能',
                                value: list[list.length - 1].positiveReactive || 0,
                                unit:'KW-h'
                            },
                        ];
                        this.params_data = params_data;
                        this.params_data_all = params_data;
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        // 获取水表数据
        getWaterHoursFn() {
            let params = {
                deptId:this.deptId,
                date: this.$moment().format('YYYY-MM-DD'),
            }
            getwaterHours(params).then(res => {
                if (res.code == 200) {
                    let list = res.data.list;
                    if (list.length > 0) {
                        let params_data = [
                            {
                                name: '用水',
                                value: list[list.length - 1].num || 0,
                                unit:'KW-h'
                            },
                        ];
                        this.params_data = params_data;
                        this.params_data_all = params_data;
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        // 获取视频设备详情
        getFvsDetailFn(id) {
            let params = {
                id
            }
            getFvsDetail(params).then(res => {
                if (res.code == 200) {
                    let item = res.data;
                    this.getFim(item)
                    this.fimFlag = true;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        //获取萤石云直播器token
        getToken() {
            let params = {
                deptId: this.deptId,
                platform: 0
            }
            getFvsToken(params).then(res => {
                if (res.code == 200) {
                    this.ezvizToken = res.data.token;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        //播放实时监控-EZUIKit
        sencePlayEZUIKitVideo(url) {
            if (this.senceEZUIKitObj) {
                this.senceEZUIKitObj.stop();
                this.senceEZUIKitObj = null;
                this.$refs['senceVideoElement2'].innerHTML = '';
            }
            let clientWidth = this.$refs['chart'].clientWidth;
            let clientHeight = this.$refs['chart'].clientHeight;
            this.senceEZUIKitObj = new EZUIKit.EZUIKitPlayer({
                id: "senceVideoElement2",
                url,
                autoplay: true,
                accessToken: this.ezvizToken,
                decoderPath: "../../../static",
                width: clientWidth,
                height: clientHeight,
                audio: 0,
            });
            this.senceEZUIKitObj.play();
        },
        close(type) {
            this.focusId = null;
            if (type == 0) {
                this.devFlag = false;
            } else if (type == 1) {
                if (this.senceHlsjs) {
                    this.$refs.senceVideoElement.pause();
                    this.senceHlsjs.destroy();
                    this.senceHlsjs = null;
                }
                if (this.senceEZUIKitObj) {
                    this.senceEZUIKitObj.stop();
                    this.senceEZUIKitObj = null;
                    this.$refs['senceVideoElement2'].innerHTML = '';
                }
                if (!this.senceHlsjs) {
                    this.fimFlag = false;
                }

            } else if (type == 2) {
                this.warnFlag = false;
            }
        },
        tabShow() {
            this.showFlag = !this.showFlag;
        },
        goto(nav, i) {
            this.navList[i].focus = !this.navList[i].focus;
            this.$forceUpdate();
        },
        // 获取现场模拟数据列表
        getSceneDetailsFn(deptId) {
            let params = {
                deptId,
            };
            getSenceDetails(params)
                .then((res) => {
                    if (res.code == 200) {
                        if (res.data) {
                            this.dataFlag = true;
                            this.detailsList = res.data.details || [];
                            this.sceneId = res.data.sceneId || "";
                            if (res.data.imgUrl) {
                                this.imgUrl = res.data.imgUrl;
                            } else {
                                this.imgUrl = "";
                            }
                            this.detailsList.map(v => {
                                v['id'] = v.objId;
                                v['label'] = v.objName;
                                v['pid'] = v.objType;
                            })
                            this.navList = initSceneTypeDataFn(this.detailsList);
                        } else {
                            this.imgUrl = "";
                            this.dataFlag = false;
                        }
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        getTag(item, index, type) {
            console.log(item)
            this.objType = item.pid;
            this.devName = item.label;
            this.params_data = [];
            if (type == 0) {
                for (let i = 0; i < this.navList.length; i++) {
                    for (let j = 0; j < this.navList[i].children.length; j++) {
                        if (this.navList[i].children[j].id == item.id) {
                            this.navList[i].focus = true;
                            this.focusId = this.navList[i].children[j].id;
                        }
                    }
                }
                this.$forceUpdate();
            } else {
                this.focusId = item.id;
            }
            if (item.pid == 4) {
                //水质检测
                this.getWaterListFn(item.id);
                this.devFlag = true;
            } else if (item.pid == 5 || item.pid == 12) {
                //环境监测仪 毒害气体
                this.getEnv(item.id);
                this.devFlag = true;
            } else if (item.pid == 6) {
                //塔基
                this.getCrane(item.id);
                this.devFlag = true;
            } else if (item.pid == 7) {
                //升降机
                let tabList = [
                    {
                        id: 1,
                        name: '左',
                    },
                    {
                        id: 2,
                        name: '右',
                    },
                ];
                this.tabList = tabList;
                this.devFlag = true;
                this.getLift(item.id);
            } else if (item.pid == 8) {
                //龙门吊
                let tabList = [
                    {
                        id: 1,
                        name: '大车运行状态',
                    },
                    {
                        id: 2,
                        name: '小车运行状态',
                    },
                    {
                        id: 3,
                        name: '其他状态',
                    },
                ];
                this.tabList = tabList;
                this.devFlag = true;
                this.tabType = '1';
                this.getGantryMonitorFn(item.id);
            } else if (item.pid == 9) {
                //架桥机
                let tabList = [
                    {
                        id: 1,
                        name: '前天车运行状态',
                    },
                    {
                        id: 2,
                        name: '后天车运行状态',
                    },
                    {
                        id: 3,
                        name: '整机运行状态',
                    },
                    {
                        id: 4,
                        name: '其他状态',
                    },
                ];
                this.tabList = tabList;
                this.devFlag = true;
                this.tabType = '1';
                this.getBridgeMonitorFn(item.id);
            } else if (item.pid == 10) {
                //履带吊
                let tabList = [
                    {
                        id: 1,
                        name: '基础数据',
                    },
                    {
                        id: 2,
                        name: ' 预警状态',
                    },
                    {
                        id: 3,
                        name: '动作开关',
                    },
                    {
                        id: 4,
                        name: '行程开关',
                    },
                ];
                this.tabList = tabList;
                this.devFlag = true;
                this.tabType = '1';
                this.getCrawlerLatestFn(item.id);
            } else if (item.pid == 20) {
                //视频监控
                this.getFvsDetailFn(item.id);
            } else if (item.pid == 30) {
                //智能水表
                this.getWaterHoursFn();
                this.devFlag = true;
            } else if (item.pid == 31) {
                //智能电表
                this.getElecHoursFn();
                this.devFlag = true;
            } else if (item.pid == 32) {
                //智能电箱
                let tabList = [
                    {
                        id: 1,
                        name: '温度',
                    },
                    {
                        id: 2,
                        name: ' 电压',
                    },
                    {
                        id: 3,
                        name: '电流',
                    },
                    {
                        id: 4,
                        name: '漏电',
                    },
                ];
                this.tabList = tabList;
                this.tabType = '1';
                this.getEnergyElectricBoxLogFn(item.id);
                this.devFlag = true;
            }
        },
        //获取环境监测仪
        getEnv(id) {
            let params = {
                id: id
            }
            getDustDateList(params).then(res => {
                if (res.code == 200) {
                    this.pm25 = res.data.pm25;
                    this.pm10 = res.data.pm10;
                    this.atmos = res.data.atmos;
                    this.noise = res.data.noise;
                    this.envTemp = res.data.envTemp;
                    this.envRh = res.data.envRh;
                    this.windDirection = wind_Direction(res.data.windDirection)[0];
                    this.windForce = wind_Force(res.data.windSpeed);
                    this.windSpeed = res.data.windSpeed;
                    this.tsp = res.data.tsp;
                    this.co = res.data.co;
                    this.co2 = res.data.co2;
                    this.h2s = res.data.h2s;
                    this.ch4 = res.data.ch4;
                    this.o2 = res.data.o2;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        //获取水质检测数据
        getWaterListFn(id) {
            let params = {
                id: id
            }
            getWaterList(params).then(res => {
                if (res.code == 200) {
                    this.ss = res.data.ss;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        //获取塔基
        getCrane(id) {
            let params = {
                craneId: id
            }
            getCraneDateLatest(params).then(res => {
                if (res.code == 200) {
                    if (res.data != undefined) {
                        let obj = res.data;
                        let params_data = initParamsData(crane_params_data, obj)
                        this.params_data = params_data.filter(v => this.tabType == v.type);
                        this.params_data_all = params_data;
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        //获取升降机
        getLift(id) {
            let params = {
                liftId: id
            }
            getLiftDateLatest(params).then(res => {
                if (res.code == 200) {
                    if (res.data.list.length > 0) {
                        let list = res.data.list;
                        list.map(v => v['type'] = v.liftSide);

                        let left_arr = list.filter(v => 1 == v.type);
                        let right_arr = list.filter(v => 2 == v.type);

                        let left_obj = left_arr.length > 0 ? left_arr[0] : {};
                        let right_obj = right_arr.length > 0 ? right_arr[0] : {};
                        this.tabType = left_arr.length > 0 ? '1' : '2';

                        let left_params = initParamsData(lift_params_data, left_obj).filter(v => 1 == v.type);
                        let right_params = initParamsData(lift_params_data, right_obj).filter(v => 2 == v.type);
                        this.params_data_all = [...left_params, ...right_params];
                        this.params_data = this.params_data_all.filter(v => this.tabType == v.type);
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        //获取视频监控
        getFim(item) {
            let params = {
                id: item.id
            }
            getStreamUrl(params).then(res => {
                if (res.code == 200) {
                    let url;
                    this.playModeFlag = false;
                    if (item.playMode === 2) {
                        this.playModeFlag = true;
                        url = res.data.ezopen;
                        this.sencePlayEZUIKitVideo(url);
                        console.log('sencePlayEZUIKitVideo')
                    } else {
                        this.playModeFlag = false;
                        if (res.data.playUrl) {
                            url = res.data.playUrl;
                            this.$refs.senceVideoElement.setAttribute('src', url)
                        } else {
                            url = res.data.hls;
                            this.senceShowVideo(url);
                            console.log('showVideo')
                        }
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        senceShowVideo(url) {
            let _this = this;
            let video = this.$refs.videoElement2; //定义挂载点
            if (hlsjs.isSupported()) {
                this.senceHlsjs = new hlsjs();
                this.senceHlsjs.loadSource(url);
                this.senceHlsjs.attachMedia(video);
                this.senceHlsjs.on(hlsjs.Events.MANIFEST_PARSED, () => {
                    video.play();
                });
                this.senceHlsjs.on(hlsjs.Events.ERROR, function (event, data) {
                    switch (data.type) {
                        // 网络错误导致的错误，据观察这种类型的错，占比最高
                        case Hls.ErrorTypes.NETWORK_ERROR:
                            // 根据自己业务（心跳/错误次数 需要加载还是重新请求，这里只给出简单的，加载情况作为示例）
                            _this.senceHlsjs.startLoad();
                            break;
                        case Hls.ErrorTypes.MEDIA_ERROR:
                            // 多媒体错误
                            _this.senceHlsjs.recoverMediaError();
                            break;
                        default:
                            _this.senceHlsjs.destroy();
                            _this.$nextTick(() => {
                                // 非网络或多媒体错误，重新获取url
                                _this.senceShowVideo(url);
                            })
                            break;
                    }
                })
            } else {
                this.$message.error("不支持的格式");
                return;
            }
        },
        getDevDetails() {
            if (this.objType == 5) {
                this.$router.push({
                    path: './../env/data',
                    query: {
                        id: this.focusId,
                    }
                })
            } else if (this.objType == 6) {
                this.$router.push({
                    path: './../fse/craneMonitor',
                    query: {
                        id: this.focusId,
                    }
                })
            } else if (this.objType == 7) {
                this.$router.push({
                    path: './../fse/liftMonitor',
                    query: {
                        id: this.focusId,
                    }
                })
            }
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize',  this.resizeFn);
    },
    mounted() {
        this.getProportion();
        window.addEventListener("resize",this.resizeFn );
    },
}
